package com.ljj.admin.exception.handler;

import com.ljj.admin.common.utils.PermissionUtils;
import com.ljj.admin.common.utils.ServletUtils;
import com.ljj.admin.web.bean.common.AjaxResult;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.exceptions.TemplateInputException;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * 自定义全局异常处理
 * @ControllerAdvice 注解，可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute，并应用到所有@RequestMapping中
 *
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger= LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder)
    {

    }

    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model)
    {

    }


    /**
     * 权限校验失败  请求为ajax 返回json  普通请求返回 跳转页面
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(AuthorizationException.class)
    public Object handleAuthorizationException(HttpServletRequest request, AuthorizationException e)
    {
        logger.error(e.getMessage(),e);
        // 判断请求是否是ajax 请求
        if(ServletUtils.isAjaxRequest(request))
        {
            return AjaxResult.error(PermissionUtils.getMsg(e.getMessage()));
        }else
        {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("/403");
            return modelAndView;
        }

    }


    /**
     * 请求方式不支持
     * @param e
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public AjaxResult handleNotSupportedException(HttpRequestMethodNotSupportedException e)
    {
        logger.error(e.getMessage(), e);
        return AjaxResult.error("不支持' " + e.getMethod() + "'请求");
    }


    /**
     * 运行时异常
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRunTimeException(RuntimeException e){

        logger.error(e.getMessage(), e);
        return AjaxResult.error("服务器错误，请联系管理员");
    }





    @ExceptionHandler(TemplateInputException.class)
    public AjaxResult handleTemplateInputException(TemplateInputException e)
    {
        logger.error(e.getMessage(), e);
        return AjaxResult.error("服务器错误，请联系管理员");
    }











}
